package org.fuxian.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.fuxian.common.Constraints;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.StorageClass;


@SuppressWarnings("unused")
public class AliyunOssUtil {


    /**
     * 获取oss服务器相关信息
     */
    private static String ENDPOINT = Constraints.POINT;
    private static String ACCESS_KEY_ID = Constraints.KEY_ID;
    private static String ACCESS_KEY_SECRET = Constraints.KEY_SECRET;
    private static String BUCKET_NAME = Constraints.BUCKET_NAME;
    private static String FILE_DIR = Constraints.FOLDER;
    private static String WEB_URL = Constraints.WEB_URL;


    private static OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

    public static FileResult upload(File file) {
        System.out.println("=========>OSS文件上传开始：" + file.getName());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if (null == file) {
            return null;
        }

        //获取文件扩展名
        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);

        PutObjectResult result = null;
        try {
            //容器不存在，就创建
            /*if(!ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }*/
            //创建文件路径
            String fileUrl = FILE_DIR + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());


            result = uploadFileOSS(file, fileUrl);
            if (null != result) {
            	 System.out.println("==========>OSS文件上传成功,OSS地址：" + fileUrl);

                FileResult fr =new FileResult(
                        file.length(),//文件大小
                        fileUrl,//文件的绝对路径
                        WEB_URL + "/" + fileUrl,//文件的web访问地址
                        suffix,//文件后缀
                        BUCKET_NAME,//存储的bucket
                        file.getName(),//原文件名
                        FILE_DIR//存储的文件夹
                );
                fr.setResult(result);
                return fr;
            }
        } catch (OSSException oe) {
            System.err.println(oe.getMessage());
        } catch (ClientException ce) {
        	System.err.println(ce.getMessage());
        } finally {
            //关闭
           // ossClient.shutdown();
        }
        return null;
    }

    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    public static FileResult upload(MultipartFile file) {

        FileResult fileResult = null;

        if (file.getSize() > 1024 * 1024 * 20) {
            //return "图片太大";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_TOO_MAX);
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        String originalFilename = file.getOriginalFilename();
        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();

        //创建文件路径
        String fileUrl = FILE_DIR + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + originalFilename);
        PutObjectResult result = null;
        try {
            result = uploadFileOSS(file.getInputStream(), fileUrl);
            if(result != null){
                fileResult = new FileResult(
                        file.getSize(),//文件大小
                        fileUrl,//文件的绝对路径
                        WEB_URL + "/" + fileUrl,//文件的web访问地址
                        suffix,//文件后缀
                        BUCKET_NAME,//存储的bucket
                        file.getName(),//原文件名
                        FILE_DIR//存储的文件夹
                );
                fileResult.setResult(result);
            }

        } catch (Exception e) {
           e.printStackTrace();
        }
        return fileResult;
    }


    /**
     * 上传多个图片
     *
     * @param files
     * @return
     */
    public static FileResult upload(List<MultipartFile> files) {

        String imgsPath = "";
        String imgsWebUrl = "";

        FileResult fileResult = null;
        if(files != null && files.size() > 0){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = format.format(new Date());

            fileResult = new FileResult(
                    null,//文件大小
                    null,//文件的绝对路径
                    null,//文件的web访问地址
                    null,//文件后缀
                    BUCKET_NAME,//存储的bucket
                    null,//原文件名
                    FILE_DIR//存储的文件夹
            );

            for(int i = 0; i < files.size(); i++){
                MultipartFile file = files.get(i);
                String originalFilename = file.getOriginalFilename();
                String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();

                //创建文件路径
                String fileUrl = FILE_DIR + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + originalFilename);
                PutObjectResult result = null;
                try {
                    result = uploadFileOSS(file.getInputStream(), fileUrl);
                    if(result != null){
                        //   upload/1.jpg,upload/2.jpg,upload/3.jpg
//                        imgsPath += i==0?"":"," + fileUrl;
                        if("".equals(imgsPath))
                            imgsPath = fileUrl;
                        else
                            imgsPath+=Constraints.FILE_FLAG+fileUrl;

                        // http://dreamer01.aling/.../1.jpg, http://lafldjslfjalsfj.jpg
//                        imgsWebUrl += i==0?"":"," + WEB_URL + "/" + fileUrl;
                        if ("".equals(imgsWebUrl))
                            imgsWebUrl = WEB_URL+File.separator+fileUrl;
                        else
                            imgsWebUrl +=Constraints.FILE_FLAG+WEB_URL+File.separator+fileUrl;

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            fileResult.setFileAPUrl(imgsPath);
            fileResult.setWebUrl(imgsWebUrl);
        }

        return fileResult;

    }

    /**
     * 上传图片获取fileUrl
     *
     * @param instream
     * @param fileName
     * @return
     */
    private static PutObjectResult uploadFileOSS(InputStream instream, String fileName) {

        PutObjectResult result = null;
        try {
            // 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName.substring(fileName.lastIndexOf("/") + 1));
            //上传文件
            //设置权限 这里是公开读
            //ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, instream, objectMetadata);

            // 上传文件
            result = ossClient.putObject(putObjectRequest);


        } catch (IOException e) {
        	System.err.println(e.getMessage());
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            /*if(ossClient != null){
                ossClient.shutdown();
            }*/
        }

        return result;
    }

    /**
     * 上传图片获取fileUrl
     *
     * @param file
     * @param fileName
     * @return
     */
    private static PutObjectResult uploadFileOSS(File file, String fileName) {


        PutObjectResult result = null;
        try {
            // 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.length());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName.substring(fileName.lastIndexOf("/") + 1));
            //上传文件

            //设置权限 这里是公开读
            //ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, file, objectMetadata);

            // 上传文件。
            result = ossClient.putObject(putObjectRequest);


        } catch (Exception e) {
        	System.err.println(e.getMessage());
        } finally {

            /*if(ossClient != null){
                ossClient.shutdown();
            }*/
        }

        return result;
    }
}
